/**
 ** This file is part of FK Klistret Extensions. FK Klistret Extensions 
 ** is free software: you can redistribute it and/or modify it under the 
 ** terms of the GNU General Public License as published by the Free 
 ** Software Foundation, either version 3 of the License, or (at your option) 
 ** any later version.

 ** FK Klistret Extensions is distributed in the hope that it will be 
 ** useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 ** General Public License for more details. You should have received a
 ** copy of the GNU General Public License along with FK Klistret Extensions. 
 ** If not, see <http://www.gnu.org/licenses/>
 */
package se.fk.klistret.migrate.utility;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Helper class to parse dates from Matrix exported data, remove quotes from
 * exported records, and create StreamSource from file paths.
 * 
 * @author Matthew Young
 * 
 */
public class FileHelper {

	/**
	 * SLF4J logger
	 */
	private static final Logger logger = LoggerFactory
			.getLogger(FileHelper.class);

	/**
	 * Parses a String representation of a date into a Java Date
	 * 
	 * @param value
	 * @return Date (even null)
	 */
	public static Date parseDate(String value) {
		if (value.equals("")) {
			logger.debug("String value [{}] parsed to null", value);
			return null;
		}

		SimpleDateFormat dateFormatter = new SimpleDateFormat(
				"yyyy-MM-dd-HH.mm.ss");

		try {
			return dateFormatter.parse(value);
		} catch (ParseException e) {
			logger.warn("Parsing string value [{}] to date failed: {}", value,
					e);
		}

		return new Date();
	}

	/**
	 * Strips quotes from data records
	 * 
	 * @param value
	 * @return String
	 */
	public static String removeQuotes(String value) {
		return value.equals("") ? value : value
				.substring(1, value.length() - 1);
	}

	/**
	 * Generates a StreamSource from file paths
	 * 
	 * @param exportFileName
	 * @param directory
	 * @return StreamSource
	 */
	public static StreamSource parseConfiguration(String exportFileName,
			String directory) {
		String fileName = exportFileName.substring(
				exportFileName.indexOf("'") + 1,
				exportFileName.lastIndexOf("'"));

		return new StreamSource(new File(directory, fileName));
	}
}
